package net.eyra.negocio.dao;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.JDBCConnectionException;

class HibernateUtil {

    private static SessionFactory sessionFactory = null;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (MappingException e) {
            System.out.print(e.getMessage());
            throw new HibernateException(e);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    protected static Session getSession() throws EyraDaoException {
        Session session = null;
        if (sessionFactory != null && !sessionFactory.isClosed()) session = sessionFactory.openSession();
        try {
            if (session != null && session.isOpen() && session.isConnected()) {
                return session;
            } else {
                sessionFactory = null;
                sessionFactory = new Configuration().configure().buildSessionFactory();
                return getSession();
            }
        } catch (JDBCConnectionException e) {
            sessionFactory = null;
            sessionFactory = new Configuration().configure().buildSessionFactory();
            return getSession();
        } catch (MappingException e) {
            System.out.print(e.getMessage());
            throw new EyraDaoException("Error de mapeos de la BD.", e);
        }
    }

}
